package cn.lyjuan.archetypes.bms.web.service;


import cn.lyjuan.archetypes.bms.web.mapper.IWebManageMapper;
import cn.lyjuan.archetypes.bms.web.mapper.IWebPrivilegeMapper;
import cn.lyjuan.archetypes.bms.web.util.ErrUtils;
import cn.lyjuan.archetypes.bms.web.util.SuperAdminUtils;
import cn.lyjuan.base.util.StringUtils;
import cn.lyjuan.archetypes.bms.common.entity.MgManage;
import cn.lyjuan.archetypes.bms.common.mapper.MgManageMapper;
import cn.lyjuan.archetypes.bms.common.mapper.MgManageRoleMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ly on 2015/1/9.
 */
@Service("mgManageService")
public class ManageService extends BaseService<MgManage>
{
    private static Logger log = LogManager.getLogger(ManageService.class.getName());

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private MgManageMapper manageMapper;

    @Autowired
    private MgManageRoleMapper manageRoleMapper;

    @Autowired
    private IWebManageMapper webManageMapper;

    @Autowired
    private IWebPrivilegeMapper webPrivilegeMapper;

    public void updateStatus(Integer id, Integer status)
    {
        webManageMapper.updateStatusById(id, status);
    }

    /**
     * 查看管理员创建的管理员
     * @param currUser
     * @return
     */
    public List<MgManage> queryManages(MgManage currUser)
    {
        List<MgManage> list = null;

        return queryManages(currUser, null, 1, Integer.MAX_VALUE);
    }

    /**
     * 查看管理员创建的管理员
     *
     * @param currUser
     * @return
     */
    public Page<MgManage> queryManages(MgManage currUser, Map<String, String> param, Integer pn, Integer ps)
    {
        List<MgManage> list = null;

        PageHelper.startPage(pn, ps);
        if (SuperAdminUtils.isAdmin(currUser.getName()))// 超级管理员可以查看所有权限
            list = webManageMapper.selectAllManages(param);
        else
            list = webManageMapper.selectManagesForCreater(currUser.getName(), param);

        return (Page<MgManage>) list;
    }

    /**
     * 添加管理员
     *
     * @param creater 创建者信息
     * @param manage
     * @return
     */
    public MgManage addManage(MgManage creater, MgManage manage)
    {
        manage.setName(manage.getName().trim());// 去首尾空格

        // 判断该账号是否存在
        MgManage manageExist = queryManageByName(manage.getName());
        if (null != manageExist)
            ErrUtils.appThrow("账号已存在");

        manage.setCreateby(creater.getName());
        manage.setCreatetime(new Date());
        manage.setLastmodifypwdtime(new Date());

        manage.setPwd(passwordEncoder.encode(manage.getPwd()));

        manageMapper.insert(manage);

        return manage;
    }

    /**
     * 更新管理员信息
     *
     * @param fromManage 被修改用户，修改前的信息
     * @param toManage   被修改用户，修改后信息
     */
    @PostAuthorize("#fromManage.createby == principal.username" +// 当前用户创建的用户
            " or #fromManage.name == principal.username")// 当前用户
    public void saveManage(MgManage fromManage, MgManage toManage)
    {
        if (!StringUtils.isNull(toManage.getPwd()))// 修改了密码
        {
            toManage.setPwd(passwordEncoder.encode(toManage.getPwd()));
            toManage.setLastmodifypwdtime(new Date());
        }

        toManage.setId(fromManage.getId());
        toManage.setName(null);// 不可修改账号

        manageMapper.updateByPrimaryKeySelective(toManage);
    }

    /**
     * 根据账号查询管理员
     *
     * @param name
     * @return
     */
    @PostAuthorize("returnObject.name == principal.username" +// 当前用户
            " or returnObject.createby == principal.username")// 被当前用户创建的用户
    public MgManage queryManageByName(String name)
    {
        Example example = new Example(MgManage.class);
        example.createCriteria()
                .andEqualTo("name", name);

        return selectOneByExample(example);
    }


}
